package com.jxmcloud.business.cut.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.jxmcloud.business.cut.util.MyTool;
import com.jxmcloud.business.cut.vo.InviteCodeVo;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@Slf4j
public class UserEncryptionHandler {
    public static String generateInviteCode(Long uid, Long actId) throws UnsupportedEncodingException {
        JSONObject inviteCode = new JSONObject();
        inviteCode.set("uid", uid);
        inviteCode.set("actId", actId);
        String encode = MyTool.desEncrypt(inviteCode.toString());
        String urlEncode = URLEncoder.encode(encode, "UTF-8");
        log.info("uid: {}, actId: {}, 生成邀请码: {}", uid, actId, urlEncode);
        return urlEncode;
    }

    public static InviteCodeVo getInviteCode(String inviteCode) throws UnsupportedEncodingException {
        log.info("接收到的邀请码: {}", inviteCode);
        String myCode = UserEncryptionHandler.decodeIfNecessary(inviteCode);

        String data = MyTool.desDecrypt(myCode);
        if (ObjectUtil.isNull(data)) {
            return null;
        }
        // 将解密后的JSON字符串转换为对象
        try {
            JSONObject json = new JSONObject(data);
            InviteCodeVo result = new InviteCodeVo();
            result.setUid(json.getLong("uid"));
            result.setActId(json.getLong("actId"));
            log.info("解析邀请码成功: {}", result);
            return result;
        } catch (Exception e) {
            log.error("解析邀请码失败: {}", e.getMessage());
            return null;
        }
    }

    public static String decodeIfNecessary(String inviteCode) throws UnsupportedEncodingException {
        String decodedCode = inviteCode;
        if (inviteCode.contains("%")) {
            try {
                decodedCode = URLDecoder.decode(inviteCode, "UTF-8");
                log.info("URLDecoder.decode后的邀请码: {}", decodedCode);
            } catch (IllegalArgumentException e) {
                decodedCode = inviteCode;
            }
        }
        return decodedCode;
    }
}
